package com.android.canvasproject.model.services;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.database.SQLException;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.RelativeLayout;

import com.android.canvasproject.R;
import com.android.canvasproject.model.dao.ProviderDaoOpenHelper;
import com.android.canvasproject.model.entity.Postit;
import com.android.canvasproject.view.utils.ComponentViewUtil;
import com.android.canvasproject.view.utils.ConstantsAction;

public class PostitService extends AsyncTask<Object, Void, List<View>> {
	
	private Activity activity;
	private ProgressDialog asyncdialog;
	private RelativeLayout canvasModelProject;
	
	public PostitService(Activity activity) {
		this.activity = activity;
		this.asyncdialog = new ProgressDialog(activity);
//		canvasModelProject = (RelativeLayout) activity.findViewById(R.id.project_model_canvas);
	}

	@Override
	protected void onPreExecute() {
		asyncdialog.setMessage("Loading...");
		asyncdialog.show();

		super.onPreExecute();
	}
	
	@Override
	protected List<View> doInBackground(Object... params) {
		ProviderDaoOpenHelper provider = new ProviderDaoOpenHelper(activity);
		List<View> postits = new ArrayList<View>();

		canvasModelProject = (RelativeLayout) params[1];

		try {
			List<Map<String, Object>> result = provider.findFilter(Postit.PostitDao.TB_POSTIT, Postit.PostitDao.COLS_POSTIT, "id_canvas = " + params[0]);
			for(Map<String, Object> map : result){
				Postit p = Postit.entityStructure(map);
				postits.add(ComponentViewUtil.createNewPostit(activity, p.getPositionX(), p.getPositionY(), p));
			}

		} catch (SQLException e) {
			Log.e(Postit.PostitDao.TB_POSTIT, ConstantsAction.Database.QUERY, e);

		} finally {
			provider.cleanup();
		}
		return postits;
	}
	
	@Override
	protected void onPostExecute(List<View> result) {
		int i = 0;
		int timeRender = 0;

		for(View v : result){
//			CanvasProjectActivity.relative.addView(v);
			canvasModelProject.addView(v);

			if(i < result.size()){
				Animation anime = AnimationUtils.loadAnimation(activity, R.anim.fade_in);
				timeRender += 30;
				anime.setStartOffset(timeRender);
				v.startAnimation(anime);
			}

			i++;
		}
		asyncdialog.dismiss();
	}
}